<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <List  @select="handleSelect" style="margin: 6px 0 6px 6px;flex:0 0 280px;" />
    <div class="ztable" style="flex: 1">


      <vxe-toolbar ref="xToolbar" export refresh custom >
        <template #buttons>
          <vxe-input v-model="taskTable.filterName" placeholder="请输入名称" @keyup="searchEvent"></vxe-input>
          <vxe-button status="primary">查 询</vxe-button>
          <vxe-button @click="insertEvent(-1)">新 增</vxe-button>
          <vxe-button @click="$refs.xTable.setAllTreeExpand(true)">展 开</vxe-button>
          <vxe-button @click="$refs.xTable.clearTreeExpand()">折 叠</vxe-button>
<!--          <vxe-button @click="$refs.xTable.toggleTreeExpand(tableData[0], true)">切换第一个</vxe-button>-->
<!--          <vxe-button @click="$refs.xTable.setTreeExpand(tableData[2], true)">展开第三个</vxe-button>-->
        </template>
        <template #tools>
<!--          <vxe-button type="text" icon="vxe-icon&#45;&#45;question" class="tool-btn"></vxe-button>-->
<!--          <vxe-button type="text" icon="vxe-icon&#45;&#45;funnel" class="tool-btn" @click="alert(1)"></vxe-button>-->
          <button style="margin-right: 10px" @click="importEvent" class="vxe-button type--button size--small is--circle" type="button" title="导入">
            <i class="vxe-button--icon vxe-icon--upload"></i>
          </button>
        </template>
      </vxe-toolbar>

      <vxe-table
        resizable
        show-overflow
        ref="xTable"
        :export-config="exportConfig"
        :tree-config="{transform: true}"
        :edit-config="{trigger: 'click', mode: 'row'}"
        :checkbox-config="{labelField: 'id'}"
        :data="taskTable.tableData">
        <vxe-column width="35">
          <template #default>
              <span class="drag-btn" style="text-align: center">
                <i class="vxe-icon--menu"></i>
              </span>
          </template>
<!--          <template #header>-->
<!--            <vxe-tooltip v-model="taskTable.showHelpTip" content="按住后可以上下拖动排序！" enterable>-->
<!--              <i class="vxe-icon&#45;&#45;question" @click="taskTable.showHelpTip = !taskTable.showHelpTip"></i>-->
<!--            </vxe-tooltip>-->
<!--          </template>-->
        </vxe-column>
        <vxe-column field="name" tree-node title="任务名称" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input v-model="row.name" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="size" title="负责人" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input v-model="row.size" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="date" title="截止时间" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input v-model="row.date" type="date" transfer></vxe-input>
          </template>
        </vxe-column>

        <vxe-column title="操作" width="100" show-overflow header-align="center" align="right">
          <template #default="{ row }">
<!--            <PlusSquareOutlined @click="addEvent({pid:row.id,pname:row.name},openDrawer)" style="font-size: 15px;margin-left: 10px;color: #52C41A"/>-->
            <PlusSquareOutlined @click="insertRow(row, 'bottom')" style="font-size: 15px;margin-left: 10px;color: #52C41A"/>
            <FormOutlined @click="editEvent({id:row.id},openDrawer)" style="font-size: 15px;margin-left: 11px;color: #2874C5"/>
            <DeleteOutlined  @click="removeEvent(row)" style="font-size: 15px;margin-left: 10px;color: #ED6F6F"/>
          </template>
        </vxe-column>
      </vxe-table>

      <!--      <vxe-table-->
      <!--          ref="xCate"-->
      <!--          resizable-->
      <!--          show-overflow-->
      <!--          row-key-->
      <!--          height="auto"-->
      <!--          highlight-current-row-->
      <!--          highlight-hover-row-->
      <!--          @cell-click="cellClickEvent"-->
      <!--          :edit-config="{trigger: 'click', mode: 'row'}"-->
      <!--          :tree-config="taskTable.tableTreeConfig"-->
      <!--          :data="taskTable.tableData">-->
      <!--        <vxe-column field="name" title="Name" tree-node :edit-render="{}">-->
      <!--          <template #default="{ row }">-->
      <!--            <vxe-input v-model="row.name" type="text"></vxe-input>-->
      <!--          </template>-->
      <!--        </vxe-column>-->
      <!--        <vxe-column field="size" title="Size" :edit-render="{}">-->
      <!--          <template #edit="{ row }">-->
      <!--            <vxe-input v-model="row.size" type="text"></vxe-input>-->
      <!--          </template>-->
      <!--        </vxe-column>-->
      <!--        <vxe-column field="type" title="Type" :edit-render="{}">-->
      <!--          <template #edit="{ row }">-->
      <!--            <vxe-input v-model="row.type" type="text"></vxe-input>-->
      <!--          </template>-->
      <!--        </vxe-column>-->
      <!--        <vxe-column field="date" title="Date" :edit-render="{}">-->
      <!--          <template #edit="{ row }">-->
      <!--            <vxe-input v-model="row.date" type="date" transfer></vxe-input>-->
      <!--          </template>-->
      <!--        </vxe-column>-->
      <!--      </vxe-table>-->


      <!--      -->
      <!--      <vxe-grid ref='xGrid' v-bind="gridOptions">-->
      <!--        <template #tbtns>-->
      <!--          <vxe-input v-model="formData.name" placeholder="输入名称查询"></vxe-input>-->
      <!--          <vxe-button @click="searchEvent" status="primary">查 询</vxe-button>-->
      <!--          <vxe-button @click="addEvent({ cate:{id:formData.cateid,name:formData.catename}},openDrawer)">新 增</vxe-button>-->
      <!--          <vxe-button @click="deleteEvent($refs.xGrid)">删 除</vxe-button>-->
      <!--        </template>-->
      <!--        <template #name_default="{ row }">-->
      <!--          <span style="cursor:pointer;color: #3e9ece"-->
      <!--                @click="editEvent({id:row.id},openDrawer)">{{ row.name }}</span>-->
      <!--        </template>-->
      <!--      </vxe-grid>-->
      <!--      -->


    </div>
    <Edit @register="registerDrawer" @success="handleSuccess" />
  </PageWrapper>
</template>
<script lang="ts">
export default { name: "PsTaskMain", inheritAttrs: false, customOptions: {} };
</script>
<script lang="ts" setup>
import {DeleteOutlined, FormOutlined, PlusSquareOutlined} from '@ant-design/icons-vue';
import { PageWrapper } from "/@/components/Page";
import List from "./list.vue";
import { nextTick, onMounted, onUnmounted, reactive, ref } from "vue";
import { VxeToolbarInstance, VxeTableInstance, VXETable } from "vxe-table";
import Edit from "./edit.vue";
import { useDrawer } from "/@/components/Drawer";
import { deleteEvent, addEvent, editEvent, createOption } from "/@/comps/vxe/list";
import Sortable from "sortablejs";
import { defHttp } from "/@/utils/http/axios";
import { useGlobSetting } from "/@/hooks/setting";
import { UploadApiResult } from "/@/api/sys/model/uploadModel";
import XEUtils from "xe-utils";


const taskTable = reactive({
  filterName: "",
  tableData: [
    { id: 10000, parentId: null, name: "test abc1", type: "mp3", size: 1024, date: "2020-08-01" },
    { id: 10050, parentId: null, name: "Test2", type: "mp4", size: null, date: "2021-04-01" },
    { id: 24300, parentId: 10050, name: "Test3", type: "avi", size: 1024, date: "2020-03-01" },
    { id: 20045, parentId: 24300, name: "test abc4", type: "html", size: 600, date: "2021-04-01" },
    { id: 10053, parentId: 24300, name: "test abc96", type: "avi", size: null, date: "2021-04-01" },
    { id: 24330, parentId: 10053, name: "test abc5", type: "txt", size: 25, date: "2021-10-01" },
    { id: 21011, parentId: 10053, name: "Test6", type: "pdf", size: 512, date: "2020-01-01" },
    { id: 22200, parentId: 10053, name: "Test7", type: "js", size: 1024, date: "2021-06-01" },
    { id: 23666, parentId: null, name: "Test8", type: "xlsx", size: 2048, date: "2020-11-01" },
    { id: 23677, parentId: 23666, name: "Test7", type: "js", size: 1024, date: "2021-06-01" },
    { id: 23671, parentId: 23677, name: "Test7", type: "js", size: 1024, date: "2021-06-01" },
    { id: 23672, parentId: 23677, name: "Test7", type: "js", size: 1024, date: "2021-06-01" },
    { id: 23688, parentId: 23666, name: "Test7", type: "js", size: 1024, date: "2021-06-01" },
    { id: 23681, parentId: 23688, name: "Test7", type: "js", size: 1024, date: "2021-06-01" },
    { id: 23682, parentId: 23688, name: "Test7", type: "js", size: 1024, date: "2021-06-01" }
  ],
  originData: [] as any[],
  tableTreeConfig: {
    transform: true,
    children: "children",
    rowKey: "id",
    indent: 15,
    parentKey: "parentId",
    iconOpen: "vxe-icon--arrow-bottom",
    iconClose: "vxe-icon--arrow-right"
  }
});

//
// const taskTable = reactive({
//   tableData: [
//     { id: 10000, parentId: null, name: 'test abc1', type: 'mp3', size: 1024, date: '2020-08-01' },
//     { id: 10050, parentId: null, name: 'Test2', type: 'mp4', size: null, date: '2021-04-01' },
//     { id: 24300, parentId: 10050, name: 'Test3', type: 'avi', size: 1024, date: '2020-03-01' },
//     { id: 20045, parentId: 24300, name: 'test abc4', type: 'html', size: 600, date: '2021-04-01' },
//     { id: 10053, parentId: 24300, name: 'test abc96', type: 'avi', size: null, date: '2021-04-01' },
//     { id: 24330, parentId: 10053, name: 'test abc5', type: 'txt', size: 25, date: '2021-10-01' },
//     { id: 21011, parentId: 10053, name: 'Test6', type: 'pdf', size: 512, date: '2020-01-01' },
//     { id: 22200, parentId: 10053, name: 'Test7', type: 'js', size: 1024, date: '2021-06-01' },
//     { id: 23666, parentId: null, name: 'Test8', type: 'xlsx', size: 2048, date: '2020-11-01' },
//     { id: 23677, parentId: 23666, name: 'Test7', type: 'js', size: 1024, date: '2021-06-01' },
//     { id: 23671, parentId: 23677, name: 'Test7', type: 'js', size: 1024, date: '2021-06-01' },
//     { id: 23672, parentId: 23677, name: 'Test7', type: 'js', size: 1024, date: '2021-06-01' },
//     { id: 23688, parentId: 23666, name: 'Test7', type: 'js', size: 1024, date: '2021-06-01' },
//     { id: 23681, parentId: 23688, name: 'Test7', type: 'js', size: 1024, date: '2021-06-01' },
//     { id: 23682, parentId: 23688, name: 'Test7', type: 'js', size: 1024, date: '2021-06-01' },
//     { id: 24555, parentId: null, name: 'test abc9', type: 'avi', size: 224, date: '2020-10-01' },
//     { id: 24566, parentId: 24555, name: 'Test7', type: 'js', size: 1024, date: '2021-06-01' },
//     { id: 24577, parentId: 24555, name: 'Test7', type: 'js', size: 1024, date: '2021-06-01' }
//   ],
//   tableTreeConfig: {
//     children: 'children',
//     rowKey: 'id',
//     indent: 15,
//     parentKey: 'parentId',
//     iconOpen: 'vxe-icon--arrow-bottom',
//     iconClose: 'vxe-icon--arrow-right'
//   }
// })

//
// const xGrid = ref({} as VxeGridInstance)
// const formData = reactive({
//   name: '',
//   listid: '',
//   listname: '',
// })
//
// const gridOptions = reactive<VxeGridProps>(createOption('/ps/task/main', {}, formData, [
//   {type: 'checkbox', align: 'center', width: 42, fixed: 'left'},
//   {type: 'seq', align: 'center', width: 50, fixed: 'left'},
//   {field: 'name', title: '任务名称', width: 300, fixed: 'left', slots: {default: 'name_default'}},
//   {field: 'notes', title: '备注'},
//   {field: 'crtim', title: '创建时间', width: 140},
//   {field: 'uptim', title: '更新时间', width: 140},
// ]));
//
// const searchEvent = () => {
//   xGrid.value.commitProxy('query')
// }
//
let stageid = '';
async function handleSelect(node) {
  console.log(node)
  if(node&&node.id){
    stageid=node.id
    taskTable.tableData=await defHttp.get({url:"/ps/task/main?stageid="+node.id});
  }else{
    stageid='';
  }
  // if(node!=null){
  //   formData.listid = node.id;
  //   formData.listname = node.name;
  // }else{
  //   formData.listid = '';
  //   formData.listname = '';
  // }
  // searchEvent();
}

//--------------------------------------------------------------------------------------------------
const [registerDrawer, {openDrawer}] = useDrawer();
//
function handleSuccess(item) {

  console.log(item);
  searchEvent();
}

const xTable = ref({} as VxeTableInstance);
const xToolbar = ref({} as VxeToolbarInstance);
let sortable1: any;

const rowDrop = () => {
  const $table = xTable.value;
  sortable1 = Sortable.create($table.$el.querySelector(".body--wrapper>.vxe-table--body tbody"), {
    handle: ".drag-btn",
    onEnd: (sortableEvent) => {
      const newIndex = sortableEvent.newIndex as number;
      const oldIndex = sortableEvent.oldIndex as number;
      const currRow = taskTable.tableData.splice(oldIndex, 1)[0];
      taskTable.tableData.splice(newIndex, 0, currRow);
    }
  });
};

// const xtools={
//   name:'11'
// }

const { apiUrl } = useGlobSetting();
const exportConfig = {
  remote: true,
  types: ["xlsx"],
  modes: ["current", "selected", "all"],
  // 自定义服务端导出
  exportMethod({ options }) {
    defHttp.getAxios().request({
      url: apiUrl+"/ps/task/main/exp/11",
      method: "get",
      data: {},
      responseType: "blob"
    }).then(res => {
      let blob = new Blob([Object.prototype.toString.call(res.data).toLowerCase() === "[object object]" ? JSON.stringify(res.data) : res.data]);
      VXETable.saveFile({ filename: options.filename, type: options.type, content: blob });
    }).catch(() => {
      VXETable.modal.message({ content: "导出失败！", status: "error" });
    });
  }
};

const importConfig={
  remote: true,
  types: ['xlsx'],
  modes: ['insert'],
  // 自定义服务端导入
  importMethod ({ file }) {
    const formBody = new FormData()
    formBody.append('file', file)
    return defHttp.post('https://api.xuliangzhan.com:10443/demo/api/pub/import', formBody).then(data => {
      VXETable.modal.message({ content: `成功导入 ${data.result.insertRows} 条记录！`, status: 'success' })
      // 导入完成，刷新表格
      // $grid.commitProxy('query')
    }).catch(() => {
      VXETable.modal.message({ content: '导入失败，请检查数据是否正确！', status: 'error' })
    })
  }
}

const importEvent =async () => {
  const { file } = await VXETable.readFile();
  const formBody = new FormData()
  formBody.append('file', file)

  await defHttp.uploadFile<UploadApiResult>(
    {
      url: apiUrl+'/ps/task/main/imp',
    },
    {file:file},
  )

  // return defHttp.post({url:'/ps/task/main/imp',data:formBody}).then(data => {
  //   VXETable.modal.message({ content: `成功导入 条记录！`, status: 'success' })
  //   // 导入完成，刷新表格
  // }).catch(() => {
  //   VXETable.modal.message({ content: '导入失败，请检查数据是否正确！', status: 'error' })
  // })

}



let initTime: any;
nextTick(() => {
  // 加载完成之后在绑定拖动事件
  initTime = setTimeout(() => {
    rowDrop();
  }, 500);

});

onMounted(()=>{
  const $table = xTable.value;
  const $toolbar = xToolbar.value;
  $table.connect($toolbar);
})

onUnmounted(() => {
  clearTimeout(initTime);
  if (sortable1) {
    sortable1.destroy();
  }
});

const handleSearch = () => {
  const filterName = XEUtils.toValueString(taskTable.filterName).trim()
  if (filterName) {
    const options = {children: 'children'}
    const searchProps = ['name']
    taskTable.tableData = XEUtils.searchTree(taskTable.originData, item => searchProps.some(key => XEUtils.toValueString(item[key]).indexOf(filterName) > -1), options)
    nextTick(() => {
      const $table = xTable.value
      $table.setAllTreeExpand(true)
    })
  } else {
    taskTable.tableData = taskTable.originData
  }
}

const searchEvent = XEUtils.debounce(function () {
  handleSearch()
}, 500, {leading: false, trailing: true})

async function fetch() {
  taskTable.originData = await defHttp.get({url: '/sys/auth/menu/tree'});
  handleSearch()
}


const insertEvent = async (row: any) => {
  if (stageid == '') {
    await VXETable.modal.message({content: '请先选择阶段', status: 'warning'});
    return;
  }
  const $table = xTable.value;
  const record = {
    id: guid().replaceAll("-",""),
    name: '',
    type:'new',
    stageid: stageid,
    parentId:null
  }
  const {row: newRow} = await $table.insertAt(record, row)
  await $table.setActiveCell(newRow, 'name');
}

const insertEvent2 = async (row: any) => {
  console.log(row)
  const $table = xTable.value;
  const record = {
    id: guid().replaceAll("-",""),
    name: '',
    type:'new',
    stageid: stageid,
    parentId:row.id
  }
  const {row: newRow} = await $table.insertAt(record, -1);
  await $table.setRowExpand(newRow, true);
  await $table.setActiveCell(newRow, 'name')
}

const insertRow = async (currRow: any, locat: string) => {
  const $table = xTable.value
  // 如果 null 则插入到目标节点顶部
  // 如果 -1 则插入到目标节点底部
  // 如果 row 则有插入到效的目标节点该行的位置
  if (locat === 'current') {
    const record = {
      name: '新数据',
      id: Date.now(),
      parentId: currRow.parentId, // 父节点必须与当前行一致
      date: XEUtils.toDateString(new Date(), 'yyyy-MM-dd')
    }
    const { row: newRow } = await $table.insertAt(record, currRow)
    await $table.setActiveRow(newRow) // 插入子节点
  } else if (locat === 'top') {
    const record = {
      name: '新数据',
      id: Date.now(),
      parentId: currRow.id, // 需要指定父节点，自动插入该节点中
      date: XEUtils.toDateString(new Date(), 'yyyy-MM-dd')
    }
    const { row: newRow } = await $table.insert(record)
    await $table.setTreeExpand(currRow, true) // 将父节点展开
    await $table.setActiveRow(newRow) // 插入子节点
  } else if (locat === 'bottom') {
    const record = {
      name: '新数据',
      id: Date.now(),
      stageid: stageid,
      parentId: currRow.id, // 需要指定父节点，自动插入该节点中
      date: XEUtils.toDateString(new Date(), 'yyyy-MM-dd')
    }
    const { row: newRow } = await $table.insertAt(record, -1)
    await $table.setTreeExpand(currRow, true) // 将父节点展开
    // await $table.setActiveRow(newRow) // 插入子节点
    await $table.setActiveCell(newRow, 'name')
  }
}


const removeEvent = async (row: any) => {
  const type = await VXETable.modal.confirm('您确定要删除该数据?')
  if (type === 'confirm') {
    const $table = xTable.value
    await $table.remove(row)
  }
}

function guid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    let r = Math.random() * 16 | 0,
        v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

</script>

